# -*- coding:utf-8 -*-
import os,sys
import re
import traceback
import time
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir, os.pardir))
import supeanut_config
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir))
from CommonLib.mylog import mylog
from CommonLib.StockTool import StockTool
from CommonLib.db.MongoDBTool import MongoDBTool


'''
作者：supeanut
创建时间：2016-xx-xx xx:xx:xx
功能描述：
	xxx
	xxxxx
相关配置：
	supeanut_config.XXX
历史改动：
	2016-xx-xx: xxxxxx
'''
class BasicTool:
	# init what
	def __init__(self):
		self.stocktool = StockTool()
		self.mongoDB = supeanut_config.MONGO_DB
		self.collMap = {"day":supeanut_config.MONGO_COLL_DAYDATA,
						"5min":supeanut_config.MONGO_COLL_5MINDATA}

	# Input: code="300033",start_datetime="2017-07-01 00:00:00"
	# Output:Flag,OriItemList:[datetime,open,close,high,low,vol_stock,vol_capital]
	def getOriItemList(self, code, index_tag=False, period="day", start_datetime=None, end_datetime=None):
		# 规范化查找模式
		if start_datetime is not None and len(start_datetime) == 10:
			start_datetime = start_datetime + " 00:00:00"
		if end_datetime is not None and len(end_datetime) == 10:
			end_datetime = end_datetime + " 99:99:99"
		projection_list = ["datetime", "open", "close", "high", "low"]
		if index_tag is False:
			projection_list.append("vol_stock")
			code = self.stocktool.get_stock_market(code) + code
		else:
			projection_list.append("vol_capital")
			code = "in" + code
		if start_datetime is None and end_datetime is None:
			filter_dict = {"code":code}
		elif start_datetime is None:
			filter_dict = {"code":code, "datetime":{"$lte":end_datetime}}
		elif end_datetime is None:
			filter_dict = {"code":code, "datetime":{"$gte":start_datetime}}
		else:
			filter_dict = {"code":code, "datetime":{"$lte":end_datetime,"$gte":start_datetime}}
		# mongo查询
		mongodb_obj = MongoDBTool(None)
		flag, msg = mongodb_obj.conn(self.mongoDB, self.collMap[period])
		if flag is False:
			return False, msg
		try:
			docs_iter = mongodb_obj.coll.find(filter=filter_dict, projection=projection_list)
		except:
			return False, traceback.format_exc()
		# 处理返回结果 str->float
		result_list = []
		for doc in docs_iter:
			# 对应projection_list
			item_list = [doc["datetime"].encode("utf-8")]
			for i in range(1, 6):
				item_list.append(float(doc[projection_list[i]]))
			result_list.append(item_list)
		# --排序
		result_list.sort(key = lambda k:k[0])
		return True, result_list

	# 以datetime为key
	def tran2Dict(self, itemList):
		itemDict = {}
		for item in itemList:
			datetime = item[0]
			itemDict[datetime] = item[1:]
		return itemDict



if __name__ == '__main__':
	obj = BasicTool()
	flag, itemList = obj.getOriItemList("600000", False, "day", None, "2017-02-28")
	print itemList
	#iitemDict = obj.tran2Dict(itemList)
	exit()
	flag, itemList = obj.getOriItemList("000001", True, "day", None, None)
	#flag, itemList = obj.getOriItemList("000001", True, "day", "2017-01-03", "2017-02-28")
	print itemList
